package indi.mozping.alternatelyprint.lockcondition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author by mozping
 * @Classname Test
 * @Description TODO
 * @Date 2019/10/17 15:06
 */
public class Test {

    private static char[] charsArr1 = "12345".toCharArray();
    private static char[] charsArr2 = "ABCDE".toCharArray();
    private static Lock lock = new ReentrantLock();
    private static Condition condition1 = lock.newCondition();
    private static Condition condition2 = lock.newCondition();

    public static void main(String[] args) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                try {
                    //2个线程会交替在for循环里面执行，打印完毕之后到for循环外面，通过signal保证线程都能够退出
                    for (int i = 0; i < charsArr1.length; i++) {
                        System.out.print(charsArr1[i]);
                        condition2.signal();
                        condition1.await();
                    }
                    //保证另一个线程退出
                    condition2.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }

            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                try {
                    for (int i = 0; i < charsArr2.length; i++) {
                        System.out.print(charsArr2[i]);
                        condition1.signal();
                        condition2.await();
                    }
                    //保证另一个线程退出
                    condition1.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }).start();
    }
}